﻿using System;
using System.Collections.Generic;

using System.Windows;
using System.Windows.Controls;

using System.Windows.Input;
using System.Windows.Navigation;

using EagleJournal.Controls;
using EagleJournalBE.Database.Tables;
using System.ComponentModel;
using System.Threading;

namespace EagleJournal
{
	public partial class DialogViewClient : UserControl
    {
        public static readonly  RoutedEvent
            InvokeDialogConfirmEvent = EventManager.RegisterRoutedEvent("InvokeDialogConfirm", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(DialogViewClient));
        public event            RoutedEventHandler
            InvokeDialogConfirm
        {
            add     { this.AddHandler(InvokeDialogConfirmEvent, value); }
            remove  { this.RemoveHandler(InvokeDialogConfirmEvent, value); }
        }

        int                 vCount                      = 0;
        bool                isLoaded                    = false;
        TableClient         clients                     = new TableClient();

        public List<int>    AffectedClients             = new List<int>();

		public              DialogViewClient            ()
		{
			this.InitializeComponent();
		}

        private     void    ButtonCancel_Click          (object sender, RoutedEventArgs e)
        {
            this.RaiseEvent(new RoutedEventArgs(InvokeDialogConfirmEvent));
        }
        private     void    ButtonSelect_Click          (object sender, RoutedEventArgs e)
        {
            this.AffectedClients.Clear();
            foreach (ListClientInfo info in this.DataFringe.Items)
            {
                if (info.Visibility == System.Windows.Visibility.Visible)
                    AffectedClients.Add(info.ClientID);
            }

            this.RaiseEvent(new RoutedEventArgs(InvokeDialogConfirmEvent));
        }

        private     void    UserControl_Loaded          (object sender, RoutedEventArgs e)
        {
            if (!this.isLoaded)
            {
                this.isLoaded = true;
            }
        }

        public      void    ClearData                   ()
        {
            this.DataFringe.Items.Clear();
            this.DataClient.Items.Clear();

            this.ButtonAddClient.IsEnabled      = false;
            this.ButtonRemoveClient.IsEnabled   = false;
        }
        public      void    PassData                    (List<int> affectedClients)
        {
            if (affectedClients == null)
                this.AffectedClients = new List<int>();
            else
                this.AffectedClients = affectedClients;

            LoadData(string.Empty);
        }

        private     void    ButtonAddClient_Click       (object sender, RoutedEventArgs e)
        {
            // remove from source
            ((ListClientInfo)this.DataClient.SelectedItem).Visibility = Visibility.Collapsed;

            int cID = ((ListClientInfo)this.DataClient.SelectedItem).ClientID;

            // add to destination
            foreach (ListClientInfo item in this.DataFringe.Items)
            {
                if (cID == item.ClientID)
                    item.Visibility = System.Windows.Visibility.Visible;
            }

            vCount++;
            if (vCount <= 0)
                this.ButtonConfirm.IsEnabled = false;
            else
                this.ButtonConfirm.IsEnabled = true;
        }
        private     void    ButtonRemoveClient_Click    (object sender, RoutedEventArgs e)
        {
            // remove from destination
            ((ListClientInfo)this.DataFringe.SelectedItem).Visibility = System.Windows.Visibility.Collapsed;

            int cID = ((ListClientInfo)this.DataFringe.SelectedItem).ClientID;

            // add to source
            foreach (ListClientInfo item in this.DataClient.Items)
            {
                if (cID == item.ClientID)
                    item.Visibility = System.Windows.Visibility.Visible;
            }

            vCount--;
            if (vCount <= 0)
                this.ButtonConfirm.IsEnabled = false;
            else
                this.ButtonConfirm.IsEnabled = true;
        }

        private     void    TextSearch_TextChanged      (object sender, TextChangedEventArgs e)
        {
            if (this.TextSearch.Text.Length > 0)
            {
                this.TextTitle.Text = "Search results";

                LoadData(this.TextSearch.Text);
            }
            else
            {
                this.TextTitle.Text = "Manage clients";

                LoadData(string.Empty);
            }
        }

        private     void    DataClient_SelectionChanged (object sender, SelectionChangedEventArgs e)
        {
            if (this.DataClient.SelectedIndex != -1)
            {
                this.ButtonAddClient.IsEnabled = true;
            }
            else
            {
                this.ButtonAddClient.IsEnabled = false;
            }
        }
        private     void    DataFringe_SelectionChanged (object sender, SelectionChangedEventArgs e)
        {
            if (this.DataClient.SelectedIndex != -1)
            {
                this.ButtonRemoveClient.IsEnabled = true;
            }
            else
            {
                this.ButtonRemoveClient.IsEnabled = false;
            }
        }

        private     void    LoadData                    (string filter)
        {
            BackgroundWorker bWorker = new BackgroundWorker();
            bWorker.WorkerReportsProgress = true;

            bWorker.DoWork              += new DoWorkEventHandler((o, dwea) =>
            {
                Dispatcher.Invoke(new Action(() =>
                    {
                        this.DataClient.Items.Clear();
                        this.DataFringe.Items.Clear();

                    }), null);

                this.clients.Refresh();

                if (!string.IsNullOrEmpty(filter))
                    Dispatcher.Invoke(new Action(() => { this.clients.Filter("clientName LIKE '%" + this.TextSearch.Text + "%'"); }), null);

                foreach (List<object> row in this.clients.TableData)
                {
                    ClientInformation cInfo = new ClientInformation()
                    {
                        ID              = (int)     row[0],
                        Name            = (string)  row[1],
                        Notifications   = 0,
                    };

                    bWorker.ReportProgress(0, cInfo);

                    Thread.Sleep(25);
                }
            });
            bWorker.ProgressChanged     += new ProgressChangedEventHandler((o, pcea) =>
            {
                ClientInformation cInfo = (ClientInformation)pcea.UserState;

                ListClientInfo listInfo = new ListClientInfo()
                {
                    ClientID    = cInfo.ID,
                    Content     = cInfo.Name,
                };
                this.DataClient.Items.Add(listInfo);

                ListClientInfo frngInfo = new ListClientInfo()
                {
                    ClientID    = cInfo.ID,
                    Content     = cInfo.Name,

                    Visibility  = Visibility.Collapsed,
                };
                this.DataFringe.Items.Add(frngInfo);
            });
            bWorker.RunWorkerCompleted  += new RunWorkerCompletedEventHandler((o, rwcea) =>
            {
                foreach (int clientID in this.AffectedClients)
                {
                    foreach (ListClientInfo info in this.DataClient.Items)
                        if (info.ClientID == clientID)
                        {
                            info.Visibility = Visibility.Collapsed;

                            break;
                        }

                    foreach (ListClientInfo info in this.DataFringe.Items)
                        if (info.ClientID == clientID)
                        {
                            info.Visibility = Visibility.Visible;

                            break;
                        }
                }
            });
            bWorker.RunWorkerAsync();
        }
	}
}
